<template>
  <div class="page">
    <div class="chat-container-box" id="chatMsgBox">
      <div class="chat-box" >
        <chat-message v-for="(msg, index) in chatMessageList"
                      :key="index"
                      :message="msg"
                      @insertCode="handleInsertCode"
                      @copyCode="handleCopyCode"
                      @reSendMessage="reSendMessage"
        ></chat-message>
        <chat-message v-if="requestStatus&&isMessageDone" :message="{role:'assistant',content:''}">
          <i class="el-icon-loading"></i>
          <span>思考中...</span>
        </chat-message>
        <chat-message v-if="requestStatus&&!isMessageDone" :message="{role:'assistant',content:nowMessage,reasoningContent:nowReasoningMessage}">
        </chat-message>
      </div>
    </div>

    <div>
      <div class="bottom-send-box">
        <div class="send-box">
          <div class="send-input">
            <el-input
                v-model="question"
                autosize
                type="textarea"
                placeholder="请输入"
                maxlength="1000"
                @keydown.native="enterSendMsg"
                ref="questionInput"
                id="questionInput"
                @focus="msgInputFocus"
            ></el-input>
          </div>
          <div class="send-btn" @click="$refs.questionInput.focus()">
            <div class="select-box" @click.stop>
              <el-select placeholder="请选择" size="mini" ref="activeModel" id="activeModel" v-model="activeModel2" @change="activeModel=activeModel2" @click.native="inputFocus">
                <el-option
                    v-for="item in activeModels"
                    :key="item"
                    :label="item"
                    :value="item">
                </el-option>
              </el-select>
              <el-input v-model="activeModel" @blur="changeModel" prefix-icon="el-icon-cpu" class="input" id="ModelInput" placeholder="请选择或输入模型名" size="mini"></el-input>
            </div>
            <el-tooltip content="请先停止" v-model="showStopTip" placement="top" effect="light" v-if="requestStatus">
              <div class="stop"  @click.stop="stopMsg">
                <div class="s"></div>
              </div>
            </el-tooltip>
            <el-button icon="el-icon-s-promotion" class="send" circle size="medium"  @click.stop="sendMsg" v-else></el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import newline from "markdown-it/lib/rules_inline/newline.mjs";

const chatMessage = require("@/components/chatMessage/index.vue").default
import {postMessage} from "@/utils/hxHandler";
import {sendMessage} from "@/api/index";
const clipboardy = require('clipboardy');
export default {
  name: "index",
  components: {
    chatMessage
  },
  data() {
    return {
      chatMsgBox:null,
      scrollTimer:null,
      autoScrollEnabled:true,
      question: '',
      chatMessageList:[],
      showStopTip:false,
      activeModel2:''
    }
  },
  computed: {
    requestStatus(){
      return this.$store.state.app.requestStatus
    },
    isMessageDone(){
      return this.$store.state.app.isMessageDone
    },
    activeModel:{
      get(){
        return this.$store.state.app.activeModel
      },
      set(val){
        this.$store.commit('app/setActiveModel',val)

        postMessage({
          command:'updateModelName',
          data:val
        })

      }
    }
  },
  watch: {
    chatHistoryMessage:{
      handler(newVal,oldVal){
        this.chatMessageList = newVal
      },
      deep:true,
      immediate:true
    },
    nowMessage:{
      handler(newVal,oldVal){
        if (this.autoScrollEnabled){
          this.smartScroll()
        }
      }
    }
  },
  mounted() {
    this.chatMsgBox = document.getElementById('chatMsgBox')
    // 监听聊天窗口滚动事件
    chatMsgBox.addEventListener('scroll', () => {
      const threshold = 50; // 距离底部的阈值(像素)
      const isNearBottom =
          chatMsgBox.scrollHeight - chatMsgBox.scrollTop <=
          chatMsgBox.clientHeight + threshold;

      this.autoScrollEnabled = isNearBottom;
    });

  },
  methods: {
    msgInputFocus(){
      // 获取当前活动窗口项目信息
      console.log('获取当前活动窗口项目信息')
      postMessage({
        command:'getProjectInfo',
        data:''
      })
    },
    inputFocus(){
      document.querySelector('#ModelInput').focus()
    },
    stopMsg(){
      this.$store.dispatch('app/stopMsg',true)
    },
    isOnlyWhitespace(str) {
      return /^\s*$/.test(str);
    },
    reSendMessage(){
      if (this.requestStatus){
        this.showStopTip = true
        setTimeout(()=>{
          this.showStopTip=false
        },1000)
        return
      }
      this.$store.dispatch('app/reSendMessage')
      sendMessage(this.chatMessageList[this.chatMessageList.length-1].content)
      this.goChatBottom()
    },
    enterSendMsg(e){
      if (e.key === 'Enter') {
        if (e.ctrlKey || e.metaKey) { // metaKey 兼容 Mac 的 Command 键
          const textarea = document.querySelector('#questionInput');
          const startPos = textarea.selectionStart;
          const endPos = textarea.selectionEnd;
          this.question =
              this.question.substring(0, startPos) +
              '\n' +
              this.question.substring(endPos);
          // 移动光标到新行
          this.$nextTick(() => {
            textarea.selectionStart = textarea.selectionEnd = startPos + 1;
          });
        }else{
          e.preventDefault();
          this.sendMsg()
        }
      }
    },
    sendMsg(e){
      if(!this.question||this.isOnlyWhitespace(this.question)){
        return
      }
      if (this.requestStatus){
        this.showStopTip = true
        setTimeout(()=>{
          this.showStopTip=false
        },1000)
        return
      }
      sendMessage(this.question)
      this.question = ''
      this.goChatBottom()
    },
    handleInsertCode(content) {
      postMessage({
        command:'insertCode',
        data:content
      })
    },
    handleCopyCode(content) {
      postMessage({
        command:'writeClipboard',
        data:content
      })
    },
    goChatBottom() {
      this.$nextTick(() => {
        chatMsgBox.scrollTo({
          top: chatMsgBox.scrollHeight,
          behavior: 'smooth'
        });
      });

    },
    smartScroll() {
      clearTimeout(this.scrollTimer);
      this.scrollTimer = setTimeout(this.goChatBottom, 100);
    }
  }
}



</script>

<style lang="scss" scoped>
.page{
  width: 100vw;
  height: 100vh;
  display: flex;
  position: relative;
  flex-wrap: wrap;
  overflow-x: hidden;
}

.chat-container-box{
  width: 100%;
  height: calc(100% - 130px);
  overflow-y: scroll;
  padding: 10px;
  box-sizing: border-box;
}
.chat-box{
  width: 100%;
  position: static;
}

.bottom-send-box{
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 999;
  padding: 10px;
  box-sizing: border-box;
  overflow-x:hidden;


  .send-box{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    border: 1px solid var(--inputLineColor);
    background-color: var(--inputBgColor);
    border-radius: 10px;

    :deep(.el-textarea__inner:focus){
      border: none;
      box-shadow: none;
    }
    :deep(.el-textarea__inner:hover){
      border: none;
      box-shadow: none;
    }
    :deep(.el-textarea__inner){
      border: none;
      box-shadow: none;
      background-color: var(--inputBgColor);
      padding: 10px;
      box-sizing: border-box;
      max-height: 30vh;
    }
    .send-input{
      width: 100%;

    }
    .send-btn{
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 10px;
      box-sizing: border-box;

      :deep(.send.el-button){
        background-color: var(--themeColor);
        color: #fff;
        font-size: 18px;
      }

      .select-box{
        display: inline-flex;
        position: relative;

        :deep(.el-select){
          position: relative;
          z-index: 1;
        }

        .input{
          position: absolute;
          z-index: 9;
          pointer-events: none;
        }

      }

      :deep(.el-select .el-input.is-focus .el-input__inner){
        border: none;

      }
      :deep(.el-input){
        overflow-y: hidden;

      }
      :deep(.el-input__inner){
        border: none;
        background-color:var(--inputBgColor);
        color:  var(--fontColor);
      }
      .stop{
        width: 40px;
        height: 40px;
        border-radius: 100px;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        background-color: #e74c3c;
        color: #fff;
        font-size: 18px;
      }
      .stop .s{
        display: inline-block;
        width: 12px;
        height: 12px;
        border-right: 2px;
        background-color: #fff;
      }
    }
  }
}



</style>